using System;
using UnityEngine;
using UnityEngine.UI;

public class DateTimePicker : MonoBehaviour
{
    public CalendarController calendar;
    public TimePickerScroller hourPicker;
    public TimePickerScroller minutePicker;
    public Text topSelectedText;
    public Button confirmBtn;
    public Button cancelBtn;
    public Button nowBtn;

    public Action<DateTime> OnConfirm;

    void Start()
    {
        if (confirmBtn) confirmBtn.onClick.AddListener(OnConfirmClicked);
        if (cancelBtn)  cancelBtn.onClick.AddListener(OnCancelClicked);
        if (nowBtn)     nowBtn.onClick.AddListener(OnNowClicked);

        if (calendar != null) calendar.SetParentPicker(this);
        if (hourPicker != null) { hourPicker.parentPicker = this; hourPicker.isHour = true; }
        if (minutePicker != null) { minutePicker.parentPicker = this; minutePicker.isHour = false; }

        UpdateTopText();
    }

    public void UpdateTopText()
    {
        if (calendar == null || topSelectedText == null) return;
        var dt = calendar.GetSelectedDateTime();
        topSelectedText.text = dt.ToString("yyyy-MM-dd HH:mm");
    }

    void OnConfirmClicked()
    {
        var dt = calendar.GetSelectedDateTime();
        Debug.Log("Confirmed datetime: " + dt);
        OnConfirm?.Invoke(dt);
        gameObject.SetActive(false);
    }

    void OnCancelClicked()
    {
        gameObject.SetActive(false);
    }

    void OnNowClicked()
    {
        var now = DateTime.Now;

        // 1) 先把日期与时间写回 calendar（立即更新模型）
        calendar.SetSelectedDate(now.Date);
        calendar.SetTime(now.Hour, now.Minute);

        // 2) 滚动 UI 到对应索引（平滑滚动）
        if (hourPicker != null) hourPicker.ScrollToIndex(now.Hour, true);
        if (minutePicker != null) minutePicker.ScrollToIndex(now.Minute, true);

        // 3) 立即刷新顶部显示（因为已经更新了 calendar）
        UpdateTopText();

        // 4) 让滚轮视觉立即刷新（以便选中高亮与顶部同步）
        if (hourPicker != null) hourPicker.UpdateSelectionVisuals();
        if (minutePicker != null) minutePicker.UpdateSelectionVisuals();
    }
}